package com;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class IntgenClient {

    private static final int DEFAULT_PORT = 1919;

    public static void main(String[] args) {

        if(args.length == 0){
            System.out.println("Usage: java IntgenClient host [port]");
            return;
        }

        int port;

        try {
            port = Integer.parseInt(args[0]);
        }catch (RuntimeException ex){
            port = DEFAULT_PORT;
        }

        try {

            SocketAddress addr = new InetSocketAddress(args[0],port);

            SocketChannel client = SocketChannel.open(addr);

            //此处非阻塞会出现问题
            //client.configureBlocking(false);

            ByteBuffer buffer = ByteBuffer.allocate(4);

            IntBuffer view = buffer.asIntBuffer();

            for(int expect = 0; ; expect++){

                client.read(buffer);

                int actual = view.get();

                buffer.clear();

                view.rewind();

                if(actual != expect){

                    System.out.println("error: expect " + expect + " get " + actual);

                    break;
                }

                System.out.println(actual);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
